﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace OnlineEducation.Helpers
{
    public static class LinqHelper
    {
        
            public static bool Contains(this string input, string find, StringComparison comparisonType)
            {
                return String.IsNullOrWhiteSpace(input) ? false : input.IndexOf(find, comparisonType) > -1;
            }

            public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> expression)
            {
                if (condition)
                    return source.Where(expression);
                else
                    return source;
            }

            public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string prop, string order)
            {
                var type = typeof(T);
                var property = type.GetProperty(prop, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                var parameter = Expression.Parameter(type, "p");
                var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                var orderByExp = Expression.Lambda(propertyAccess, parameter);
                MethodCallExpression resultExp = Expression.Call(typeof(Queryable),
                    order.Equals("asc", StringComparison.InvariantCultureIgnoreCase) ? "OrderBy" : "OrderByDescending",
                    new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
                return source.Provider.CreateQuery<T>(resultExp);
            }

          
        
    }
}
